﻿using System;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using ZL.Web.Utility.Config;
using ZLWeb.WebApiEntityBase;

namespace ZL.Web.Utility.Mongodb
{
    public class MongoObjectDb<T>
    {
        private string _dbname;
        private string _collectionname;
        private static string _connectionString;

        static MongoObjectDb()
        {
            _connectionString = string.Format("mongodb://{0}/?safe=true",
                ZLConfig.Mongodbserver);
            // _connectionString = string.Format("mongodb://{0}/?safe=true", MongoDBSetting.ConnectionString);
            _msever = new MongoClient(_connectionString).GetServer();

        }

        public MongoObjectDb(string dbname, string collectionname)
        {
            this._dbname = dbname;
            this._collectionname = collectionname;
        }

        private static MongoServer _msever;

        public static MongoFileDb CreateMongoDb()
        {
            return new MongoFileDb();
        }

        /// <summary>
        ///     保存对象
        /// </summary>
        /// <returns></returns>
        public void SaveObjectToMongoDb(T item)
        {
            MongoDatabase db = _msever.GetDatabase(_dbname);
            MongoCollection<BsonDocument> collection = db.GetCollection(_collectionname);
            collection.Insert(item);
        }

        /// <summary>
        /// 查询数据库,检查是否存在指定ID的对象
        /// </summary>
        /// <param name="key">对象的ID值</param>
        /// <returns>存在则返回指定的对象,否则返回Null</returns>
        public virtual MongoCursor<LogEntity> Find<LogEntity>()
        {
            MongoDatabase db = _msever.GetDatabase(_dbname);
            var collection = db.GetCollection<LogEntity>(_collectionname);
            var query = Query<ZLWeb.WebApiEntityBase.LogEntity>.LT(e => e.LogTime, DateTime.Now.AddDays(2));
            MongoCursor<LogEntity> mongoCursor = collection.Find(query);
            foreach (var item in mongoCursor)
            {
                
            }
            return mongoCursor;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Delete(LogEntity model)
        {
            MongoDatabase db = _msever.GetDatabase(_dbname);
            var collection = db.GetCollection<LogEntity>(_collectionname);
            WriteConcernResult res = collection.Remove(Query.EQ("_id", model.id));
            return res.Ok;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //public long Update(T model)
        //{
        //    BsonDocument doc = BsonExtensionMethods.ToBsonDocument(model);
        //    WriteConcernResult res = this.collection.Update(Query.EQ("_id", model.id), new UpdateDocument(doc));
        //    return res.DocumentsAffected;
        //}


    }
}